package com.tarena.lbs.stock.web.service;

import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import com.tarena.lbs.pojo.stock.po.CouponStockPO;
import com.tarena.lbs.stock.web.repository.CouponStockRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StockService {
    @Autowired
    private CouponStockRepository couponStockRepository;
    public boolean initCouponStock(CouponStockParam param) {
        //id coupon_id business_id num create_at update_at
        //将参数不全 CouponStockPO 写入数据库
        CouponStockPO poParam=new CouponStockPO();
        BeanUtils.copyProperties(param,poParam);
        poParam.setCreateAt(new Date());
        poParam.setUpdateAt(poParam.getCreateAt());
        //insert into coupon_stock (字段) values (对象)
        //持久层会返回一个整数值,表示本次写操作 影响的数据行数 insert 一条数据影响的行数 0 没增成功 1 增成功了
        int result=couponStockRepository.saveCouponStock(poParam);
        return result>0;
    }

    public boolean checkEnoughStock(Integer couponId) {
        //优惠券和库存实体数据 对应关系 1:1 select * from coupon_stock where coupon_id=#{}
        CouponStockPO po=couponStockRepository.getCouponStockByCouponId(couponId);
        if (po!=null){
            return po.getNum()>0;
        }else {
            return false;
        }
    }

    public boolean reduceStock(Integer couponId) {
        //mysql 写操作没有返回值 但是框架会根据执行写操作影响的rows 封装一个整数
        //update更新执行成功 至少有一行被影响 整数>=1 update没有执行 整数=0
        int rows=couponStockRepository.updateNumByCouponId(couponId);
        return rows>0;
    }
}
